<template>
  <div class="notice-new">
    <el-form ref="newForm" :model="newForm" label-width="150px">
      <el-form-item
        label="名称："
        prop="name"
        :rules="[{ required: true, message: '请输入名称', trigger: 'change' }]"
      >
        <el-input placeholder="请输入" v-model.trim="newForm.name"></el-input>
      </el-form-item>
      <el-form-item
        label="联系人："
        prop="contacts"
        :rules="[
          { required: true, message: '请输入联系人', trigger: 'change' },
        ]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.contacts"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="通知类型："
        prop="announcementType"
        :rules="[
          { required: true, message: '请选择通知类型', trigger: 'change' },
        ]"
      >
        <el-select v-model="newForm.announcementType" placeholder="请选择">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, index) in typeList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="内容描述："
        prop="contentDes"
        :rules="[
          { required: true, message: '请输入内容描述', trigger: 'change' },
        ]"
      >
        <el-input
          placeholder="请输入"
          type="textarea"
          rows="4"
          v-model.trim="newForm.contentDes"
        ></el-input>
      </el-form-item>
      <el-form-item label="相关附件：">
        <el-upload
          class="upload-file"
          name="file"
          accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.pdf"
          :action="config.uploadUrl"
          :file-list="fileList"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :disabled="!$store.getters.hasEditPermission"
          :data="{ token: siteInfos.token }"
        >
          <el-button size="small" type="green">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="通知状态："
        prop="state"
        :rules="[
          { required: true, message: '请选择通知状态', trigger: 'change' },
        ]"
      >
        <el-radio-group v-model="newForm.state">
          <el-radio label="0">暂存草稿</el-radio>
          <el-radio label="1">直接发布</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="接收单位：">
        <el-switch
          v-model="setUnit"
          active-color="#1B72DC"
          inactive-color="#d0cfd0"
        >
        </el-switch>
        <el-button class="ml-20" type="green" v-if="setUnit" @click="openUnit"
          >选择企业单位</el-button
        >
      </el-form-item>
      <el-form-item label="已选单位：" v-if="setUnit">
        <span
          class="selected-unit-item"
          v-for="(item, index) in selectedUnits"
          :key="index"
          @click="deleteSelectedUnit(item, index)"
          >{{ item.name }} <i class="el-icon-close"></i
        ></span>
        <p v-if="selectedUnits.length == 0" class="data-none">暂无选中企业</p>
      </el-form-item>
    </el-form>
    <!-- 选择企业单位辑 start -->
    <el-dialog
      v-if="unitModalVisible"
      class="unit-select-dialog"
      title="选择企业单位"
      :visible.sync="unitModalVisible"
      width="1000px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <Unit
        ref="unit"
        :selected="selectedUnits"
        @cancel="unitModalVisible = false"
        @confirm="confirmUnit"
      >
      </Unit>
      <div slot="footer">
        <el-button type="cancel" @click="unitModalVisible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="confirmUnitAction">确定</el-button>
      </div>
    </el-dialog>
    <!-- 选择企业单位辑 end -->
  </div>
</template>
<script>
import { mapState } from "vuex";
import Unit from "@/components/census/notice/Unit.vue";
export default {
  name: "newRecordAccount",
  props: {
    typeList: {
      type: Array,
      default() {
        return [];
      },
    },
    activeData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    ...mapState(["siteInfos"]),
  },
  components: {
    Unit,
  },
  watch: {
    activeData() {
      this.initForm();
    },
    selectedUnits(units) {
      if (units.length > 0) {
        if (units[0].id == "all") {
          this.newForm.allflag = true;
          this.newForm.bottomArea = this.selectedUnitArea;
        } else {
          this.newForm.allflag = false;
          let unitsIds = units.map((item) => {
            return item.id;
          });
          this.newForm.units = unitsIds.join(",");
        }
      }
    },
  },
  data() {
    return {
      newForm: {},
      loading: false,
      fileList: [],
      setUnit: false,
      unitModalVisible: false,
      selectedUnits: [],
      selectedUnitArea: "",
    };
  },
  methods: {
    initForm() {
      if (this.activeData) {
        this.newForm = this.utils.pick(this.activeData, [
          "id",
          "announcementType",
          "contentDes",
          "state",
          "ishaveFile",
          "fileName",
          "filePath",
          "ishaveReceivingUnit",
          "units",
          "allflag",
          "bottomArea",
        ]);
        this.newForm.state = this.newForm.state ? "1" : "0";
        if (this.newForm.ishaveFile) {
          this.fileList.push({
            name: this.newForm.fileName,
            url: this.newForm.filePath,
          });
        }
        this.setUnit = this.newForm.ishaveReceivingUnit;
        if (this.setUnit) {
          let selectedUnitIds = this.activeData.receivingUnitIds.split(",");
          let selectedUnitNames = this.activeData.receivingUnitNames.split(",");
          this.selectedUnits = selectedUnitNames.map((item, index) => {
            return {
              name: item,
              id: selectedUnitIds[index],
            };
          });
        }
      } else {
        this.newForm = {
          state: "0",
        };
        if (this.$refs["newForm"]) {
          this.$refs["newForm"].resetFields();
        }
      }
    },
    beforeUpload(file) {
      let acceptArr = ["doc", "docx", "pdf"];
      let fileName = file.name;
      fileName = fileName.split(".");
      let ext = fileName[fileName.length - 1];
      ext = ext.toLowerCase();
      let isAccept = acceptArr.indexOf(ext) >= 0;
      if (!isAccept) {
        this.$message.error("只能上传PDF或者word文件");
      }
      return isAccept;
    },
    uploadSuccess(res, file, fileList) {
      this.newForm.fileName = res.data.fileName;
      this.newForm.filePath = res.data.filePath;
    },
    uploadError(err, file, fileList) {
      let errorData = JSON.parse(err.message);
      this.$message.error(errorData.message);
    },
    handleRemove(file, fileList) {
      this.newForm.fileName = "";
      this.newForm.filePath = "";
    },
    submitAction() {
      this.$refs["newForm"].validate((valid) => {
        if (valid) {
          if (this.setUnit && this.selectedUnits.length == 0) {
            this.$message.error("请选择接收单位");
            return false;
          }
          this.$emit("submitting");
          this.loading = true;
          let params = Object.assign(
            {
              homeName: this.siteInfos.homeName,
              ishaveReceivingUnit: this.setUnit ? true : false,
            },
            this.newForm
          );
          params.ishaveFile = this.newForm.fileName ? true : false;
          this.$ajax({
            url: "/noticeAnnouncement/noticeAnnouncement/addOrUpdate",
            method: "post",
            data: params,
          }).then(
            (data) => {
              this.loading = false;
              this.$message.success("保存成功");
              this.$emit("success", data);
            },
            (error) => {
              this.$emit("fail");
              this.loading = false;
              this.$message.error(error.msg);
            }
          );
        } else {
          return false;
        }
      });
    },
    openUnit() {
      this.unitModalVisible = true;
    },
    submitSuccessAction() {},
    confirmUnitAction() {
      this.$refs.unit.confirmAction();
      this.unitModalVisible = false;
    },
    confirmUnit(selectedUnits, selectedUnitArea) {
      this.selectedUnits = selectedUnits;
      this.selectedUnitArea = selectedUnitArea;
    },
    deleteSelectedUnit(item, index) {
      this.selectedUnits.splice(index, 1);
    },
  },
  created() {
    this.initForm();
  },
};
</script>
